package org.changs.nav.ui.nav;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;

import com.amap.api.maps.model.LatLng;
import com.amap.api.services.geocoder.RegeocodeAddress;

import org.changs.aplug.utils.EmptyUtils;
import org.changs.nav.R;
import org.changs.nav.databinding.MarketDetailFragmentBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.AmapRouteHelper;

import javax.inject.Inject;

import aplug.data.db.CollectInfoHelper;
import aplug.data.db.mode.CollectInfo;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yincs on 2017/11/25.
 */

public class MarketDetailFragment extends BaseMapFragment  {
    public static final String TAG = MarketDetailFragment.class.getName();
    private static final String TAG_REGEOCODE_ADDRESS = "TAG_REGEOCODE_ADDRESS";
    private static final String TAG_POSITION = "TAG_POSITION";

    public static MarketDetailFragment newInstance(LatLng position) {
        Bundle args = new Bundle();
        args.putParcelable(TAG_POSITION, position);
        MarketDetailFragment fragment = new MarketDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private MarketDetailFragmentBinding mBinding;
    private RegeocodeAddress mRegeocodeAddress;
    private LatLng mPosition;
    private CollectInfo mCollectInfo;
    private String mMarketName = "地图选点", mMarketDes = "地图选点";
    @Inject CollectInfoHelper mCollectInfoHelper;
    @Inject MapSwitchDelegate mMapSwitchDelegate;
    @Inject AmapRouteHelper mAmapRouteHelper;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.market_detail_fragment, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPosition = getArguments().getParcelable(TAG_POSITION);
        if (savedInstanceState != null)
            mRegeocodeAddress = savedInstanceState.getParcelable(TAG_REGEOCODE_ADDRESS);

        if (mRegeocodeAddress == null) {
            showLoadingAddress();
        } else {
            showRegeocodeAddress();
        }

        mBinding.btnGoHere.setOnClickListener(v -> {
            mAmapRouteHelper.calculate(this, mMarketName, mMarketDes,
                    mPosition.latitude, mPosition.longitude);
        });

        mCollectInfoHelper.findByLatLon(mPosition.latitude, mPosition.longitude)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CollectInfo>() {
                    @Override
                    public void accept(CollectInfo collectInfo) throws Exception {
                        mCollectInfo = collectInfo;
                        setCollectState(true);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        setCollectState(false);
                    }
                });
        mBinding.btnCollect.setOnClickListener(v -> {
            mBinding.btnCollect.setEnabled(false);
            if (mCollectInfo == null) {
                mCollectInfo = new CollectInfo(null, mMarketName, mMarketDes, mPosition.latitude, mPosition.longitude);
                mCollectInfoHelper.insert(mCollectInfo)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                mMapSwitchDelegate.addCollectMarket(aLong, mPosition);
                                mCollectInfo.setId(aLong);
                                mBinding.btnCollect.setEnabled(true);
                                setCollectState(true);
                            }
                        });
            } else {
                mCollectInfoHelper.delete(mCollectInfo)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                mMapSwitchDelegate.remoteCollectMarket(mCollectInfo.getId());
                                mCollectInfo = null;
                                mBinding.btnCollect.setEnabled(true);
                                setCollectState(false);

                            }
                        });
            }
        });
    }

    private void setCollectState(boolean isCollect) {
        mBinding.ivCollect.setImageResource(isCollect ? R.mipmap.search_tip_collected : R.mipmap.search_tip_collect);
        mBinding.tvCollect.setText(isCollect ? "已收藏" : "收藏");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(TAG_REGEOCODE_ADDRESS, mRegeocodeAddress);
    }

    private void showRegeocodeAddress() {
        if (mRegeocodeAddress.getStreetNumber() != null) {
            mMarketName = mRegeocodeAddress.getDistrict() + mRegeocodeAddress.getStreetNumber().getStreet() + mRegeocodeAddress.getStreetNumber().getNumber();
        }
        if (EmptyUtils.isNotEmpty(mRegeocodeAddress.getPois())) {
            mMarketDes = mRegeocodeAddress.getPois().get(0).getSnippet();
        }
        if (mBinding.ivState.getAnimation() != null) {
            mBinding.ivState.getAnimation().cancel();
        }
        mBinding.ivState.setImageResource(R.mipmap.auto_poicard_default_bg);
        mBinding.tvName.setText(mMarketName);
        mBinding.tvAddress.setText(String.format("在%s附近", mMarketDes));
    }

    private void showLoadingAddress() {
        mBinding.ivState.setImageResource(R.mipmap.widget_drawable_nogps_loading);
        RotateAnimation rotateAnimation = new RotateAnimation(0, 360,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(800);
        rotateAnimation.setRepeatCount(-1);
        rotateAnimation.setInterpolator(new LinearInterpolator());
        mBinding.ivState.startAnimation(rotateAnimation);
        rotateAnimation.start();
        mBinding.tvName.setText("地图选点");
        mBinding.tvAddress.setText("地址获取中...");
    }

    public void setRegeocodeAddress(RegeocodeAddress regeocodeAddress) {
        mRegeocodeAddress = regeocodeAddress;
        if (getRootView() == null) return;
        showRegeocodeAddress();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapSwitchDelegate.switch2Basics();
    }

    @Override
    protected boolean getOutsideTouchable() {
        return false;
    }
}
